<template>
    <div class="platformSelect relative">
        <!-- <el-select :style="{ width: '120px' }" v-model="platform" @change="platformChange">
            <el-option v-for="item in platformList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select> -->
        <el-text class="cursor-pointer flex items-center" :class="customClass ?? 'dark:!text-[#d6d6d6]'"
            @click="popoverVisible = true">
            <!-- <component :is="PLATFORM_LIST[platform]?.icon" class="dark:fill-[#d6d6d6] w-[14px] h-[14px] mx-[8px]" />
            {{ PLATFORM_LIST[platform]?.name }}
            <el-icon ref="buttonRef" class="!w-[34px]">
                <ArrowDown />
            </el-icon> -->
            <div class="text-right max-w-[80px] break-all line-clamp-1">
                {{ username }}
            </div>
            <el-icon ref="buttonRef" class="!w-[34px]">
                <ArrowDown />
            </el-icon>
        </el-text>
        <!-- usePageVariablesStore.platform != PLATFORM_Map.data && usePageVariablesStore.platform != PLATFORM_Map.monitor -->
        <el-popover ref="popoverRef" v-model:visible="popoverVisible" popper-class="platformSelect-popper"
            :teleported="true" :show-arrow="false" :virtual-ref="buttonRef" trigger="click" placement="bottom-end"
            virtual-triggering persistent>
            <div v-for="(item, index) in platformList" :key="item.value" :class="`h-[38px] text-center py-[12px] cursor-pointer
                ${index != platformList.length - 1 ? 'border-b' : 'border-b'}
                border-solid border-[var(--el-border-color-lighter)]
                hover:bg-[var(--bg-3)] hover:!text-[var(--el-color-primary)]
                ${platform == item.value ? 'checked-item' : 'dark:text-[#d6d6d6]'} popover-item`"
                @click="platformChange(item.value)">
                <span class="h-[14px]  !text-[14px] leading-[14px] flex items-center justify-center">
                    <component :is="item?.icon"
                        class="dark:fill-[#d6d6d6] w-[14px] h-[14px] mr-[8px] popover-item-icon" />
                    {{ item.name }}
                </span>
            </div>
            <div class="h-[38px] border-b  border-solid border-[var(--el-border-color-lighter)]
            flex items-center cursor-pointer justify-center hover:bg-[var(--bg-3)]
            dark:text-[#d6d6d6] hover:!text-[var(--el-color-primary)]" @click="showSelfInfo">
                <span class="h-[14px]  !text-[14px] leading-[14px] flex items-center justify-center">
                    <!-- <IconifyIconOffline :icon="User" style="margin: 5px" /> -->
                    <component :is="userInfo"
                        class="dark:fill-[#d6d6d6] w-[14px] h-[14px] mr-[8px] popover-item-icon" />
                    个人信息
                </span>
            </div>
            <div class="h-[38px] flex items-center cursor-pointer justify-center hover:bg-[var(--bg-3)]
            dark:text-[#d6d6d6] hover:!text-[var(--el-color-primary)]" @click="logout">
                <span class="h-[14px]  !text-[14px] leading-[14px] flex items-center justify-center">
                    <!-- <IconifyIconOffline :icon="LogoutCircleRLine" style="margin: 5px" /> -->
                    <component :is="logoutSvg"
                        class="dark:fill-[#d6d6d6] w-[14px] h-[14px] mr-[8px] popover-item-icon" />
                    退出系统
                </span>
            </div>
        </el-popover>
    </div>
</template>
<script setup lang="ts">
import { userKey } from '@/utils/auth'
import { cloneDeep, deviceDetection, storageLocal } from "@pureadmin/utils";
import { PLATFORM_LIST, PLATFORM_Map } from "@/constant/index";
import { usePageVariablesStoreHook, initScreenUnit, initManageUnit, initOperateUnit } from '@/store/modules/pageVariables'
import { ArrowDown } from '@element-plus/icons-vue'
import dark from '@/assets/images/svg/dark.svg'
import { debounce } from "@pureadmin/utils";
import { message } from '@/utils/message';
import { useNav } from "@/layout/hooks/useNav";
import LogoutCircleRLine from "@iconify-icons/ri/logout-circle-r-line";
import User from "@iconify-icons/ri/user-3-fill";
import { addDialog } from "@/components/ReDialog";
import { editPassword, getSelfInfo } from '@/api/user';
import selfInfoPopup from "@/components/selfInfoPopup/selfInfoPopup.vue";
import showEditPasswordPopup from "@/components/selfInfoPopup/showEditPasswordPopup.vue";
import { ElButton } from 'element-plus';
import md5 from "blueimp-md5";
import logoutSvg from '@/assets/images/svg/logout-svg.svg'
import userInfo from '@/assets/images/svg/userInfo.svg'

const props = defineProps({
    customClass: {
        type: String,
        default: ''
    }
})

const platform = ref(null as any);
const platformList = shallowRef([] as any)
const usePageVariablesStore = usePageVariablesStoreHook()
const buttonRef = ref()
const popoverRef = ref()
const popoverVisible = ref(false)
const formRef = ref();

const { logout, username } = useNav();
onBeforeMount(() => {
    if (storageLocal().getItem(userKey).userInfo?.allowPortal) {
        storageLocal().getItem(userKey).userInfo?.allowPortal?.forEach(item => {
            PLATFORM_LIST[item] && platformList.value.push(PLATFORM_LIST[item])
        });
    } else if (storageLocal().getItem(userKey).userInfo?.isSuper == 1) {
        const myArray: [string, { name: string; value: PLATFORM_Map; }][] = Object.entries(PLATFORM_LIST);
        myArray.forEach(item => {
            platformList.value.push(item[1])
        });
    }
    platform.value = usePageVariablesStore.getPlatform()
    if (!platformList.value.find(item => item.value === platform.value)) {
        console.log(platformList.value);
        message(`暂无${PLATFORM_LIST[platform.value]?.name}权限，请联系管理员！`, { type: "warning" })
        platformChange(platformList.value[0].value)
    }
})
const platformChange = (val: number) => {
    if (val == PLATFORM_Map.data || val == PLATFORM_Map.monitor) {
        usePageVariablesStore.setScreen(null)
        initScreenUnit().finally(() => {
            usePageVariablesStore.setPlatform(val)
            window.location.reload();
        })
    } else if (val == PLATFORM_Map.manage) {
        initManageUnit().then(() => {
            usePageVariablesStore.setPlatform(val)
            window.location.reload();
            setTimeout(() => {
                let classList = document.documentElement.classList;
                classList.forEach(item => {
                    if (item.startsWith("data-dashboard-")) {
                        classList.remove(item);
                    }
                });
            }, 200)
        }).catch(() => {
            message('加载管理平台失败！', { type: "error" })
        })
    } else if (val == PLATFORM_Map.operate) {
        initOperateUnit().then(() => {
            usePageVariablesStore.setPlatform(val)
            window.location.reload();
            setTimeout(() => {
                let classList = document.documentElement.classList;
                classList.forEach(item => {
                    if (item.startsWith("data-dashboard-")) {
                        classList.remove(item);
                    }
                });
            }, 200)
        }).catch(() => {
            message('加载运行平台失败！', { type: "error" })
        })
    }
    popoverVisible.value = false
};
const showSelfInfo = () => {
    addDialog({
        title: `个人信息`,
        width: "800px",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        props: {
            formInline: {},
            isLoading: false
        },
        contentRenderer: () => h(selfInfoPopup, { ref: formRef }),
        openAutoFocus({ options, index }) {
            options.props.isLoading = true;
            getSelfInfo()
                .then(res => {
                    options.props.formInline = res.result.userInfo;
                })
                .finally(() => {
                    options.props.isLoading = false;
                });
        },
        footerRenderer({ options, index }) {
            return footerButton({ options, index });
        }
    });
};
const footerButton = ({ options, index }) => {
    return h(
        "div",
        {
            class: "flex justify-end"
        },
        [
            h(
                ElButton,
                {
                    text: false,
                    bg: true,
                    onClick: () => {
                        showEditPassword();
                    }
                },
                "修改密码"
            )
            // h(
            //   ElButton,
            //   {
            //     text: false,
            //     bg: true,
            //     onClick: () => {
            //       closeDialog(options, index, { command: "cancel" })
            //     },
            //   },
            //   "取消"
            // ),
        ]
    );
};
const showEditPassword = () => {
    addDialog({
        title: `修改密码`,
        width: "400px",
        draggable: true,
        fullscreen: deviceDetection(),
        fullscreenIcon: true,
        closeOnClickModal: false,
        props: {
            formInline: {},
            isLoading: false
        },
        contentRenderer: () => h(showEditPasswordPopup, { ref: formRef }),
        beforeSure(done, { options, index }) {
            const FormRef = formRef.value.getRef();
            const formData = options.props.formInline;
            function chores() {
                message(`操作成功`, {
                    type: "success"
                });
                done();
            }
            FormRef.validate(valid => {
                if (valid && !options.props?.isLoading) {
                    options.props.isLoading = true;
                    let cloneData = cloneDeep(formData);
                    cloneData.oldPassword = md5(cloneData.oldPassword);
                    cloneData.newPassword = md5(cloneData.newPassword);
                    cloneData.rePassword = md5(cloneData.rePassword);
                    editPassword(cloneData)
                        .then(res => {
                            if (res.code == 200) {
                                chores();
                            }
                        })
                        .finally(() => {
                            options.props.isLoading = false;
                        });
                }
            });
        }
    });
};
</script>
<style lang="scss">
.platformSelect-popper {
    padding: 0px !important;
    width: 110px !important;
    min-width: 110px !important;
    background: var(--bg-2) !important;
    border-radius: 5px;

    .el-popper__arrow::before {
        background: var(--bg-2) !important;
    }

    .checked-item {
        background-color: var(--bg-3);
        color: var(--el-color-primary) !important;

        .popover-item-icon {
            fill: var(--el-color-primary);
        }
    }

    .popover-item:hover {
        .popover-item-icon {
            fill: var(--el-color-primary);
        }
    }
}
</style>
